﻿(function ($) {
    $.askform = function (f, options) {
        this.name = f.attr("name");
        this.action = f.attr("action");
        this.countdown = f.data("countdown");
        this.language = f.data("language");
        this.dom = f;
        this.statuswidget = $("#" + this.name + "_status");
        this.uniqueID = this.action.substring(this.action.length - 36);
        this.defaults = {
            messageWidth: '300',
            messageHeight: '180',
            messageModal: true,
            duplicateRate: 101,
            enableCookie: false,
            showPreviousButton: true,
            minimumTime: 1,
            passStart: false,
            autoSave: false,
            inputValidCheck: true,
            enablePager: true,
            enableSubmit: true,
            popupMessage: true,
            serverCheck: true
        };
        this.noticemessages = {
            postError: "保存答卷数据失败，请重新提交！如果还不能提交，请更换浏览器！",
            saveSuccess: "填写的内容已经保存！请进行操作。",
            loginError: "登陆失败，请重新输入！",
            hour: "小时",
            minute: "分",
            second: "秒"
        };
        this.defaultmessages = {
            minimumTimeMessage: "您填写问卷太快了！请认真填写！",
            duplicateRateMessage: "{0}%的题目答案都是相同的，请重新修改填写。"
        };
        if (this.getUrlParam("serverCheck") != null && this.getUrlParam("serverCheck") == "false") {
            this.defaults.serverCheck = false;
        }
        if (this.getUrlParam("enablePager") != null && this.getUrlParam("enablePager") == "false") {
            this.defaults.enablePager = false;
        }
        if (this.getUrlParam("popupMessage") != null && this.getUrlParam("popupMessage") == "false") {
            this.defaults.popupMessage = false;
        }
        if (this.getUrlParam("passStart") != null && this.getUrlParam("passStart") == "true") {
            this.defaults.passStart = true;
        }
        this.settings = $.extend(true, {}, this.defaults, options);
        this.messages = $.extend(true, {}, this.defaultmessages, options);
        //section
        var sections = [];
        $(".formsection", f).each(function (num) {
            sections.push(new $.askform.section($(this), num));
        });
        this.sections = sections;

        //widgets
        var widgets = [];
        var fields = [];
        var widgetNumber = 0;
        for (section in this.sections) {
            for (widget in this.sections[section].widgets) {
                this.sections[section].widgets[widget].number = widgetNumber;
                this.sections[section].widgets[widget].inputValidCheck = this.settings.inputValidCheck;
                widgets.push(this.sections[section].widgets[widget]);
                for (field in this.sections[section].widgets[widget].fields) {
                    fields.push(this.sections[section].widgets[widget].fields[field]);
                }
                widgetNumber++;
            }
        }
        this.widgets = widgets;
        this.fields = fields;

        //pages
        this.currentPage = 0;
        this.pages = $(".formpage", this.dom);
        if (this.settings.passStart && this.pages.length > 2) {
            this.currentPage = 1;
        }

        //pager
        this.currentPager = 0;
        var pagers = [];
        var pagerWidgets = [];
        $.each(widgets, function (index, w) {
            pagerWidgets.push(w);
            if (w.type == "pager") {
                w.hide();
                var pager = new $.askform.pager(pagerWidgets);
                pagers.push(pager);
                pagerWidgets = [];
            }
        });
        if (pagerWidgets.length > 0) {
            var pager = new $.askform.pager(pagerWidgets);
            pagers.push(pager);
        }
        this.pagers = pagers;

        this.previouswrap = $("#" + this.name + '_previous');
        this.nextwrap = $("#" + this.name + '_next');
        this.submitwrap = $("#" + this.name + '_done');
        this.verifywrap = $("#" + this.name + '_verify');
        this.previousButton = $("#" + this.name + '_previousbutton');
        this.nextButton = $("#" + this.name + '_nextbutton');
        this.submitButton = $("#" + this.name + '_submit');
        this.saveButton = $("#" + this.name + '_save');
        this.pagerWrap = $("#" + this.name + '_pager');
        this.message = $("#" + this.name + '_message');
        this.startButton = $("#" + this.name + '_start');
        this.pageNextButton = $(".pagenext");
        this.pagePreviousButton = $(".pageprevious");
        this.returnButton = $("#" + this.name + '_return');
        this.loading = $("#" + this.name + '_loading');
        this.pagerView = $("#" + this.name + '_pagersview');
        this.Progressbar = $("#" + this.name + '_progressbar');
        this.ProgressText = $("#" + this.name + '_progresstext');
        this.widgetTotal = $("#" + this.name + '_widgetstotal');
        this.widgetCompleted = $("#" + this.name + '_widgetscompleted');
        this.timing = $("#" + this.name + '_timingtext');
        this.countdowntext = $("#" + this.name + '_countdowntext');
        this.duration = $("#" + this.name + '_duration');
        this.hasInitData = this.action.indexOf("EntryGuid=") > 0;
        this.disableValidation = false;

        this.init();
    }
    $.extend($.askform, {
        prototype: {
            //dialog message
            getUrlParam: function (name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return r[2]; return null;
            },
            showMessage: function (message) {
                if (message.length > 0) {
                    if (this.settings.popupMessage) {
                        this.message
                .html(message)
                .dialog({
                    width: this.settings.messageWidth,
                    height: this.settings.messageHeight,
                    modal: this.settings.messageModal
                });
                    } else {
                        alert(message);
                    }
                }
            },
            //page
            gotoPage: function (i) {
                this.pages.each(function (index, o) {
                    $(o).hide();
                });
                this.currentPage = i;
                $(this.pages[this.currentPage]).show();
                $("html,body").scrollTop(1);
            },
            pageNext: function () {
                $(this.pages[this.currentPage]).hide();
                this.currentPage++;
                if (this.settings.enableCookie) {
                    $.cookie(this.uniqueID + "page", this.currentPage, { expires: 7 });
                }
                if (this.currentPage > this.pages.length) this.currentPage = this.pages.length;
                $(this.pages[this.currentPage]).show();
                $("html,body").scrollTop(1);
            },
            pagePrevious: function () {
                $(this.pages[this.currentPage]).hide();
                this.currentPage--;
                if (this.settings.enableCookie) {
                    $.cookie(this.uniqueID + "page", this.currentPage, { expires: 7 });
                }
                if (this.currentPage < 0) this.currentPage = 0;
                $(this.pages[this.currentPage]).show();
                $("html,body").scrollTop(1);
            },
            //pager
            gotoPager: function (current, target) {
                var p = this.pagers[current];
                if (target < current || p.validate()) {
                    p.hide();
                    this.pagers[target].show();
                    if (this.pagers[target].widgets && this.pagers[target].widgets.length > 0) {
                        //this.pagers[target].widgets[0].dom.focus();
                        $('html, body').animate({ scrollTop: '0px' }, 0);
                    }
                    if (this.settings.enableCookie) {
                        $.cookie(this.uniqueID + "pager", target, { expires: 7 });
                    }
                    return true;
                }
                return false;
            },
            pagerPrevious: function () {
                if (this.gotoPager(this.currentPager, this.currentPager - 1)) {
                    this.currentPager--;
                    if (!this.pagers[this.currentPager].hasShowWidgets()) {
                        this.pagerPrevious();
                    }
                    return true;
                }
                return false;
            },
            pagerNext: function () {
                if (this.gotoPager(this.currentPager, this.currentPager + 1)) {
                    this.currentPager++;
                    if (!this.pagers[this.currentPager].hasShowWidgets() && this.currentPager < this.pagers.length - 1) {
                        this.pagerNext();
                    }
                    return true;
                }
                return false;
            },
            jump: function (current, start) {
                for (i = current + 1; i < start; i++) {
                    this.widgets[i].disabled(current);
                    this.widgets[i].hide();
                }
                for (i = start; i < this.widgets.length; i++) {
                    var disabledIndex = jQuery.inArray(current, this.widgets[i].disabledTypes);
                    if (disabledIndex >= 0) {
                        this.widgets[i].disabledTypes.splice(disabledIndex, 1);
                    }
                    if (!this.widgets[i].enabled && (this.widgets[i].disabledTypes.length == 0)) {
                        var w = this.widgets[i];
                        w.enabled = true;
                        $.each(this.pagers[this.currentPager].widgets, function (n, pw) {
                            if (pw.id == w.id) {
                                w.show();
                            }
                        });
                    }
                }
            },
            syncWidget: function (source, widget) {
                var choices = $("input:checked", source.dom);
                var target = $(".fieldrow", widget.dom);
                var count = 0;
                $.each(target, function (index, w) {
                    title = $.trim($(".fieldheader", $(w)).text());
                    isexist = false;
                    $.each(choices, function (i, c) {
                        if (title == $.trim($("label", $(c).parent()).text())) {
                            isexist = true;
                        }
                    });
                    if (isexist) {
                        $(w).show();
                        count++;
                    } else {
                        $(w).hide();
                        $("input", $(w)).removeAttr("checked");
                    }
                });
                widget.rules.max = count;
                widget.rules.min = count;
                widget.messages.min = widget.messages.required;
                widget.messages.max = widget.messages.required;
            },
            hideWidget: function (flag, widget) {
                if (widget) {
                    widget.disabled(flag);
                    widget.hide();
                }
            },
            showWidget: function (flag, widget) {
                if (widget) {
                    var disabledIndex = jQuery.inArray(flag, widget.disabledTypes);
                    if (disabledIndex >= 0) {
                        widget.disabledTypes.splice(disabledIndex, 1);
                    }
                    if (!widget.enabled && (widget.disabledTypes.length == 0)) {
                        widget.enabled = true;
                        $.each(this.pagers[this.currentPager].widgets, function (n, pw) {
                            if (pw.id == widget.id) {
                                widget.show();
                            }
                        });
                    }
                }
            },
            getWidget: function (id) {
                var widget = null;
                $.each(this.widgets, function (n, w) {
                    if (w.id == id) {
                        widget = w;
                    }
                });
                return widget;
            },
            getField: function (id) {
                var field = null;
                $.each(this.fields, function (n, f) {
                    if (f.id == id) {
                        field = f;
                    }
                });
                return field;
            },
            init: function () {
                var obj = this;
                //init pager
                if (this.pagers.length > 1 && this.settings.enablePager) {
                    this.pagerWrap.show();
                    this.verifywrap.hide();
                    this.nextButton.show();
                    this.submitButton.hide();
                    this.submitButton.closest('.ui-btn').hide();
                    this.previousButton.hide();
                    this.previousButton.closest('.ui-btn').hide();
                    for (var i in this.pagers) {
                        this.pagers[i].hide();
                    }
                    this.pagers[0].show();
                } else {
                    this.pagerWrap.hide();
                    this.nextButton.hide();
                    this.nextButton.closest('.ui-btn').hide();
                    this.previousButton.hide();
                    this.previousButton.closest('.ui-btn').hide();
                }

                if (this.settings.enableCookie && $.cookie(this.uniqueID + "page") != null) {
                    this.currentPage = $.cookie(this.uniqueID + "page");
                }
                this.gotoPage(this.currentPage);

                this.startButton.bind("click", function () {
                    obj.pageNext();
                    obj.updateStatus();
                });
                this.pageNextButton.bind("click", function () {
                    obj.pageNext();
                    obj.updateStatus();
                });
                this.returnButton.bind("click", function () {
                    obj.pagePrevious();
                });
                this.pagePreviousButton.bind("click", function () {
                    obj.pagePrevious();
                });

                this.loading
            .bind("ajaxSend", function () { $(this).show(); })
            .bind("ajaxComplete", function () { $(this).hide(); });

                this.previousButton.click(function () {
                    if (obj.pagerPrevious()) {
                        obj.updateStatus();
                        obj.nextButton.show();
                        obj.nextButton.closest('.ui-btn').show();
                        obj.verifywrap.hide();
                        obj.submitButton.hide();
                        obj.submitButton.closest('.ui-btn').hide();
                        if (obj.currentPager == 0) {
                            obj.previousButton.hide();
                            obj.previousButton.closest('.ui-btn').hide();
                        }
                    }
                });
                this.nextButton.click(function () {
                    if (obj.pagerNext()) {
                        obj.updateStatus();
                        if (obj.settings.showPreviousButton) {
                            obj.previousButton.show();
                            obj.previousButton.closest('.ui-btn').show();
                        }
                        if (obj.currentPager == obj.pagers.length - 1) {
                            obj.nextButton.hide();
                            obj.nextButton.closest('.ui-btn').hide();
                            obj.submitButton.show();
                            obj.submitButton.closest('.ui-btn').show();
                            obj.verifywrap.show();
                        }
                    }
                });

                this.pagerViewText = this.pagerView.html();
                this.widgetTotalText = this.widgetTotal.html();
                this.widgetCompletedText = this.widgetCompleted.html();
                this.timingText = this.timing.html();
                this.dom.bind("focusin", function () {
                    obj.dom.trigger("form_focusin", obj);
                });
                this.dom.bind("focusout", function () {
                    if (obj.settings.enableCookie) {
                        $.cookie(obj.name, obj.serialize(), { expires: 7 });
                    }
                    obj.updateStatus();
                    obj.dom.trigger("form_focusout", obj);
                });

                this.updateStatus = function () {
                    if (this.statuswidget) {
                        var total = this.totalEnableWidgets();
                        var completed = this.completedEnableWidgets();
                        try {
                            this.pagerView.html(this.pagerViewText.replace(/\{0\}/g, this.currentPager + 1).replace(/\{1\}/g, this.pagers.length));
                            this.Progressbar.progressbar({ value: completed / total * 100 });
                            this.ProgressText.html((completed / total * 100).toFixed(2) + "%");
                            this.widgetTotal.html(this.widgetTotalText.replace(/\{0\}/g, total));
                            this.widgetCompleted.html(this.widgetCompletedText.replace(/\{0\}/g, completed));
                        } catch (err) { }
                    }
                }
                this.updateStatus();

                //init dialog
                //var url = window.location.href;
                if (this.getUrlParam("err") != null && this.getUrlParam("err") == "0") {
                    if (this.hasInitData) {
                        $.getJSON(this.action + "&actiontype=result&callback=?" + "&timstamp=" + Math.round(new Date().getTime()),
                        function (backdata) {
                            if (backdata.message.length > 0) {
                                $("#" + obj.name + "_thankyoubody").html(backdata.message);
                                obj.sucess();
                                obj.gotoPage(obj.pages.length - 1);
                            }
                        });
                    } else {
                        obj.sucess();
                        obj.gotoPage(obj.pages.length - 1);
                    }
                } else {
                    if (this.getUrlParam("msg") != null) {
                        this.showMessage(decodeURIComponent(this.getUrlParam("msg")));
                    } else if (this.settings.serverCheck) {
                        $.getJSON(this.action + "&actiontype=message&callback=?" + "&timstamp=" + Math.round(new Date().getTime()),
                        function (backdata) {
                            obj.showMessage(backdata.message);
                        });
                    }
                }
                //init data
                if (this.hasInitData) {
                    $.ajax({
                        type: "get",
                        async: false, //控制同步            
                        url: this.action + "&actiontype=data&callback=?" + "&timstamp=" + Math.round(new Date().getTime()),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        cache: false,
                        success: function (backdata) {
                            if (backdata.formdata.length > 0) {
                                obj.unserializeForm(backdata.formdata);
                                obj.updateStatus();
                            }
                        }
                    });
                    //$.getJSON(this.action + "&actiontype=data&callback=?" + "&timstamp=" + Math.round(new Date().getTime()),
                    //function (backdata) {
                    //    if (backdata.formdata.length > 0) {
                    //        obj.unserializeForm(backdata.formdata);
                    //        obj.updateStatus();
                    //    }
                    //});
                } else if (this.settings.enableCookie && $.cookie(this.name) != null) {
                    obj.unserializeForm($.cookie(this.name));
                    obj.updateStatus();
                }

                if (this.settings.enableCookie && $.cookie(this.uniqueID + "pager") != null) {
                    if ($.cookie(this.uniqueID + "pager") > 0) {
                        var pager = $.cookie(this.uniqueID + "pager");
                        for (var i = 0; i < pager; i++) {
                            this.nextButton.click();
                        }
                    }
                }

                //save
                this.saveButton.bind("click", function () {
                    obj.saveData();
                    obj.showMessage(obj.noticemessages.saveSuccess);
                });
                //submit
                this.submitButton.bind("click", function () {
                    obj.dom.trigger("form_submit", obj);
                    if (obj.disableValidation || (obj.validate() && obj.customCheck())) {
                        if (obj.settings.enableSubmit) {
                            if (obj.action.indexOf(window.location.host) < 0) {
                                obj.submit();

                            } else {
                                obj.settings.enableSubmit = false;
                                $.ajax({
                                    type: 'POST',
                                    url: obj.action,
                                    data: obj.serialize() + "&formduration=" + obj.formduration,
                                    dataType: "json",
                                    error: function () {
                                        obj.settings.enableSubmit = true;
                                        obj.showMessage(obj.noticemessages.postError);
                                    },
                                    success: function (result) {
                                        obj.settings.enableSubmit = true;
                                        if (result.err == 0) {
                                            if (result.message.length > 0) {
                                                $("#" + obj.name + "_thankyoubody").html(result.message);
                                            }
                                            if ($("#" + obj.name + "_thankyoubody").html().indexOf("{EntryID}" > 0)) {
                                                $("#" + obj.name + "_thankyoubody").html($("#" + obj.name + "_thankyoubody").html().replace(/{EntryID}/ig, result.EntryID));
                                            }
                                            if ($("#" + obj.name + "_thankyoubody").html().indexOf("{TotalPoint}" > 0)) {
                                                $("#" + obj.name + "_thankyoubody").html($("#" + obj.name + "_thankyoubody").html().replace(/{TotalPoint}/ig, result.TotalPoint));
                                            }
                                            if ($("#" + obj.name + "_thankyoubody").html().indexOf("{EntryGuid}" > 0)) {
                                                $("#" + obj.name + "_thankyoubody").html($("#" + obj.name + "_thankyoubody").html().replace(/{EntryGuid}/ig, result.EntryGuid));
                                            }
                                            if ($("#" + obj.name + "_thankyoubody").html().indexOf("%7bEntryGuid%7d" > 0)) {
                                                $("#" + obj.name + "_thankyoubody").html($("#" + obj.name + "_thankyoubody").html().replace(/%7bEntryGuid%7d/ig, result.EntryGuid));
                                            }
                                            obj.sucess();
                                            if (result.redirecturl && result.redirecturl.length > 0) {
                                                if (result.redirecttime && result.redirecttime > 0) {
                                                    obj.gotoPage(obj.pages.length - 1);
                                                    setTimeout(function () { window.location.href = result.redirecturl; }, result.redirecttime * 1000);
                                                } else {
                                                    window.location.href = result.redirecturl;
                                                }
                                            } else {
                                                obj.gotoPage(obj.pages.length - 1);
                                            }
                                            if (obj.hasInitData) {
                                                $.getJSON(obj.action + "&actiontype=data&callback=?" + "&timstamp=" + Math.round(new Date().getTime()),
                                                function (backdata) {
                                                    if (backdata.formdata.length > 0) {
                                                        obj.unserializeForm(backdata.formdata);
                                                        obj.updateStatus();
                                                    }
                                                });
                                            }
                                        } else {
                                            obj.showMessage(result.message);
                                        }
                                    }
                                });

                            }
                        }
                    }
                    return false;
                });

                this.formduration = 0;
                setInterval(function () {
                    obj.formduration++;
                    obj.timing.val(obj.formduration);
                    try {
                        obj.timing.html(obj.timingText.replace(/\{0\}/g, parseInt(obj.formduration / 60)).replace(/\{1\}/g, (obj.formduration % 60)));
                    } catch (err) { }
                }, 1000);
                this.starttime = parseInt(this.startButton.data("starttime"));
                if (this.starttime) {
                    this.startButton.timedDisable(this.starttime * 1000);
                }

                this.formcountdown = this.countdown;
                if (this.countdown > 0) {
                    this.interValObj = setInterval(function () {
                        if (obj.formcountdown > 0) {
                            obj.formcountdown = obj.formcountdown - 1;
                            var second = Math.floor(obj.formcountdown % 60);             // 计算秒     
                            var minite = Math.floor((obj.formcountdown / 60) % 60);      //计算分 
                            var hour = Math.floor((obj.formcountdown / 3600) % 24);      //计算小时 
                            obj.countdowntext.html(hour + obj.noticemessages.hour + minite + obj.noticemessages.minute + second + obj.noticemessages.second);
                        } else {//剩余时间小于或等于0的时候，就停止间隔函数 
                            window.clearInterval(obj.interValObj);
                            obj.postData();
                            //这里可以添加倒计时时间为0后需要执行的事件 
                        }
                        //obj.timing.val(obj.formduration);
                        //obj.timing.html(obj.timingText.replace(/\{0\}/g, parseInt(obj.formduration / 60)).replace(/\{1\}/g, (obj.formduration % 60)));
                    }, 1000);
                } else {
                    this.countdowntext.parent().hide();
                }
            },
            submitLogin: function (formData) {
                var obj = this;
                $.ajax({
                    type: 'POST',
                    url: obj.action + "&actiontype=login",
                    data: $("input", formData).serialize(),
                    dataType: "json",
                    error: function () {
                        alert(obj.noticemessages.loginError);
                    },
                    success: function (result) {
                        if (result.err == 0) {
                            window.location.href = result.message;
                        } else {
                            alert(result.message);
                        }
                    }
                });
            },
            completedWidgets: function () {
                var num = 0;
                for (section in this.sections) {
                    num += this.sections[section].completedWidgets();
                }
                return num;
            },
            totalWidgets: function () {
                var num = 0;
                for (section in this.sections) {
                    num += this.sections[section].totalWidgets();
                }
                return num;
            },
            completedEnableWidgets: function () {
                var num = 0;
                for (section in this.sections) {
                    num += this.sections[section].completedEnableWidgets();
                }
                return num;
            },
            totalEnableWidgets: function () {
                var num = 0;
                for (section in this.sections) {
                    num += this.sections[section].totalEnableWidgets();
                }
                return num;
            },
            validate: function () {
                var isOK = true;
                var isFocus = false;
                for (widget in this.widgets) {
                    this.widgets[widget].isChecked = true;
                    if (!this.widgets[widget].validate()) {
                        isOK = false;
                        if (!isFocus) {
                            for (field in this.widgets[widget].fields) {
                                if (!this.widgets[widget].fields[field].valid) {
                                    $("input", this.widgets[widget].fields[field].dom)[0].focus();
                                    isFocus = true;
                                    break;
                                }
                            }
                            if (!isFocus) {
                                this.widgets[widget].dom.focus();
                                isFocus = true;
                            }
                        }
                    }
                }
                if (isOK) {
                    this.dom.trigger('form_valid', this);
                }
                return isOK;
            },
            customCheck: function () {
                for (var i in this.checkMethods) {
                    if (this.checkMethods[i]) {
                        if (!this.checkMethods[i](this)) {
                            return false;
                        }
                    }
                }
                return true;
            },
            addCustomMethod: function (name, method) {
                this.checkMethods[name] = method;
            },
            checkMethods: {
                minimumTime: function (obj) {
                    var isOK = true;
                    if (obj.formduration < obj.settings.minimumTime) {
                        isOK = false;
                        obj.showMessage(obj.messages.minimumTimeMessage);
                    }
                    return isOK;
                },
                duplicateRate: function (obj) {
                    var isOK = true;
                    var total = 0;
                    if (obj.settings.duplicateRate <= 100) {
                        var values = new Array();
                        for (field in obj.fields) {
                            var v = obj.fields[field].value;
                            if (obj.fields[field].isDuplicateCheck && v) {
                                var id = obj.fields[field].id.split("_")[0];
                                var inputs = obj.fields[field].dom.find('input[id^="' + id + '"]');
                                var vs = v.split(",");
                                var pos = 0;
                                for (i = 0; i < vs.length; i++) {
                                    if (vs[i]) {
                                        for (j = 0; j < inputs.length; j++) {
                                            if ($(inputs[j]).val() == vs[i]) {
                                                pos = j;
                                                break;
                                            }
                                        }
                                        total++;
                                        if (values[pos]) {
                                            values[pos] += 1;
                                        } else {
                                            values[pos] = 1;
                                        }
                                    }
                                }
                            }
                        }
                        var max = 0;
                        for (value in values) {
                            if (values[value] / total > max) max = values[value] / total;
                        }
                        if (max > 0 && max * 100 >= obj.settings.duplicateRate) {
                            isOK = false;
                            obj.showMessage(obj.messages.duplicateRateMessage.replace(/\{0\}/ig, (max * 100).toFixed(2)));
                        }
                    }
                    return isOK;
                }
            },
            sucess: function () {
                $.cookie(this.name, null);
                this.clear();
                this.formduration = 0;
            },
            check: function () {
                for (section in this.sections) {
                    for (widget in this.sections[section].widgets) {
                        if (!this.sections[section].widgets[widget].check()) {
                            return false;
                        }
                    }
                }
                return true;
            },
            submit: function () {
                this.dom.submit();
                return false;
            },
            postData: function () {
                var obj = this;
                $.ajax({
                    type: 'POST',
                    url: obj.action,
                    data: obj.serialize() + "&formduration=" + obj.formduration,
                    dataType: "json",
                    error: function () {
                        obj.settings.enableSubmit = true;
                        obj.showMessage(obj.noticemessages.postError);
                    },
                    success: function (result) {
                        obj.settings.enableSubmit = true;
                        if (result.err == 0) {
                            if (result.message.length > 0) {
                                $("#" + obj.name + "_thankyoubody").html(result.message);
                            }
                            if ($("#" + obj.name + "_thankyoubody").html().indexOf("{EntryID}" > 0)) {
                                $("#" + obj.name + "_thankyoubody").html($("#" + obj.name + "_thankyoubody").html().replace(/{EntryID}/ig, result.EntryID));
                            }
                            obj.sucess();
                            if (result.redirecturl && result.redirecturl.length > 0) {
                                if (result.redirecttime && result.redirecttime > 0) {
                                    obj.gotoPage(obj.pages.length - 1);
                                    setTimeout(function () { window.location.href = result.redirecturl; }, result.redirecttime * 1000);
                                } else {
                                    window.location.href = result.redirecturl;
                                }
                            } else {
                                obj.gotoPage(obj.pages.length - 1);
                            }
                            if (obj.hasInitData) {
                                $.getJSON(obj.action + "&actiontype=data&callback=?" + "&timstamp=" + Math.round(new Date().getTime()),
                                                function (backdata) {
                                                    if (backdata.formdata.length > 0) {
                                                        obj.unserializeForm(backdata.formdata);
                                                        obj.updateStatus();
                                                    }
                                                });
                            }
                        } else {
                            obj.showMessage(result.message);
                        }
                    }
                });
            },
            saveData: function () {
                var obj = this;
                if (this.hasInitData) {
                    $.ajax({
                        type: 'POST',
                        url: obj.action + "&actiontype=save",
                        data: obj.dom.serialize(),
                        dataType: "json",
                        error: function () {
                            obj.showMessage(obj.noticemessages.postError);
                        },
                        success: function (result) {
                            if (result.err == 0) {

                            } else {
                                //obj.showMessage(result.message);
                            }
                        }
                    });
                }
            },
            clear: function () {
                this.dom.find(':input').each(function () {
                    switch (this.type) {
                        case 'password':
                        case 'select-multiple':
                        case 'select-one':
                        case 'text':
                        case 'textarea':
                            $(this).val('');
                            break;
                        case 'checkbox':
                        case 'radio':
                            this.checked = false;
                    }
                });

            },
            serialize: function () {
                return this.dom.serialize();
            },
            unserializeForm: function (values) {
                if (!values) {
                    return this;
                }

                values = values.split("&");
                var serialized_values = [];
                $.each(values, function () {
                    var properties = this.split("=");
                    if ((typeof properties[0] != 'undefined') && (typeof properties[1] != 'undefined')) {
                        if (serialized_values[properties[0].replace(/\+/g, " ")]) {
                            serialized_values[properties[0].replace(/\+/g, " ")] += "," + decodeURIComponent(properties[1].replace(/\+/g, " "));
                        } else {
                            serialized_values[properties[0].replace(/\+/g, " ")] = decodeURIComponent(properties[1].replace(/\+/g, " "));
                        }
                    }
                });
                values = serialized_values;

                this.dom.find(":input,textarea,select").removeAttr('checked').each(function () {
                    var tag_name = $(this).attr("name");
                    if (values[tag_name] !== undefined) {
                        if ($(this).attr("type") == "checkbox" || $(this).attr("type") == "radio") {
                            if ((values[tag_name] + ",").indexOf($(this).attr("value") + ",") >= 0) {
                                $(this).attr("checked", "checked");
                            }
                        } else {
                            $(this).val(values[tag_name]);
                        }
                    }
                });
            }
        }
    });

    /* 
    Pager factory 
    */
    $.askform.pager = function (widgets) {
        this.widgets = widgets;
    }
    $.extend($.askform.pager, {
        prototype: {
            hide: function () {
                for (widget in this.widgets) {
                    if (this.widgets[widget].enabled) {
                        this.widgets[widget].hide();
                    }
                }
            },
            show: function () {
                for (widget in this.widgets) {
                    if (this.widgets[widget].enabled) {
                        this.widgets[widget].show();
                    }
                }
            },
            validate: function () {
                var isOK = true;
                var isFocus = false;
                for (widget in this.widgets) {
                    var nowwidget = this.widgets[widget];
                    nowwidget.isChecked = true;
                    if (!nowwidget.validate()) {
                        isOK = false;
                        if (!isFocus) {
                            nowwidget.dom.focus();
                            isFocus = true;
                        }
                    }
                }
                return isOK;
            },
            hasShowWidgets: function () {
                for (widget in this.widgets) {
                    if (this.widgets[widget].type != "pager" && this.widgets[widget].enabled) {
                        return true;
                    }
                }
                return false;
            },
            check: function () {
                for (widget in this.widgets) {
                    if (!this.widgets[widget].check()) {
                        return false;
                    }
                }
                return true;
            }
        }
    });
    /* 
    Section factory 
    */
    $.askform.section = function (sec, num) {
        var widgets = [];
        this.number = num;
        $(".formwidget", sec).each(function (index) {
            widgets.push(new $.askform.section.widget($(this), index));
        });
        this.dom = sec;
        this.widgets = widgets;
        this.init();
    }
    $.extend($.askform.section, {
        prototype: {
            init: function () {
                var obj = this;
                this.dom.bind("focusin", function () {
                    obj.dom.trigger('section_focusin', obj);
                });
                this.dom.bind("focusout", function () {
                    obj.dom.trigger('section_focusout', obj);
                });
            },
            totalWidgets: function () {
                var num = 0;
                for (widget in this.widgets) {
                    var nowwidget = this.widgets[widget];
                    if (nowwidget.fieldsNumber > 0) {
                        num++;
                    }
                }
                return num;
            },
            completedWidgets: function () {
                var num = 0;
                for (widget in this.widgets) {
                    var nowwidget = this.widgets[widget];
                    if (nowwidget.fieldsNumber > 0 && nowwidget.isValid && nowwidget.value) {
                        num++;
                    }
                }
                return num;
            },
            totalEnableWidgets: function () {
                var num = 0;
                for (widget in this.widgets) {
                    var nowwidget = this.widgets[widget];
                    if (nowwidget.fieldsNumber > 0 && nowwidget.enabled) {
                        num++;
                    }
                }
                return num;
            },
            completedEnableWidgets: function () {
                var num = 0;
                for (widget in this.widgets) {
                    var nowwidget = this.widgets[widget];
                    if (nowwidget.fieldsNumber > 0 && nowwidget.isValid && nowwidget.value && nowwidget.enabled) {
                        num++;
                    }
                }
                return num;
            },
            validate: function () {
                var isOK = true;
                for (widget in this.widgets) {
                    var nowwidget = this.widgets[widget];
                    nowwidget.isChecked = true;
                    if (!nowwidget.validate()) {
                        isOK = false;
                    }
                }
                if (isOK) {
                    this.dom.trigger('section_valid', this);
                }
                return isOK;
            },
            check: function () {
                for (widget in this.widgets) {
                    if (!this.widgets[widget].check()) {
                        return false;
                    }
                }
                return true;
            }
        }
    });
    /*
    widget factory 
    */
    $.askform.section.widget = function (f, num) {
        this.dom = f;
        this.number = num;
        this.type = f.attr("data-type") || "";
        this.id = f.attr("id");
        this.required = !!f.attr("data-required");
        this.min = Number(f.attr("data-min")) || 0;
        this.max = Number(f.attr("data-max")) || 0;
        this.minLength = Number(f.attr("data-minlength")) || 0;
        this.maxLength = Number(f.attr("data-maxlength")) || 4000;
        this.invalidWrapper = $("p.widgetmessage", f);
        this.isUnique = !!f.attr("data-isunique");
        this.refFormID = f.prop("data-refformID") || 0;
        this.pattern = f.attr("data-pattern") || "";
        this.value = f.attr("data-value") || "";
        this.patterns = {
            email: "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-])+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z0-9]{2,})|(\\.[A-Za-z0-9]{2,}\\.[A-Za-z0-9]{2,}))$",
            url: "^https?://(.+\.)+.{2,4}(/.*)?$",
            number: "^\\d{1,10}(\\.\\d{1,2})?$",
            idcard: "^((\\d{17})([0-9xX])|([A-Za-z]+\\d{6}\\([0-9aA]{1}\\)))$",
            phone: "^((\\+?\\d{1,5}-)?((\\d{11})|(\\d{7,8})|((\\d{4}|\\d{3})-(\\d{7,8}))|((\\d{4}|\\d{3})-(\\d{7,8})-(\\d{1,5}))|((\\d{7,8})-(\\d{1,5}))))$",
            date: "^(?:(?!0000)[0-9]{4}([-/])(?:(?:0?[1-9]|1[0-2])([-/])(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])([-/])(?:29|30)|(?:0?[13578]|1[02])([-/])31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-/])0?2([-/])29)$"
        };
        var fields = [];
        var obj = this;
        $(".formfield", f).each(function (index) {
            fields.push(new $.askform.section.widget.field($(this), obj));
        });
        this.fields = fields;
        this.init();
    }
    $.extend($.askform.section.widget, {
        prototype: {
            init: function () {
                var obj = this;
                this.enabled = true;
                this.disabledTypes = [];
                this.isHidden = false;
                this.inputValidCheck = true;
                this.rules = { required: this.required, pattern: this.pattern || this.patterns[this.type] || "" },
                this.messages = { required: this.invalidWrapper.attr("data-required"), pattern: this.invalidWrapper.attr("data-validation") }
                this.isChecked = false;
                this.isValid = false;
                this.fieldsNumber = this.numberOfFields();
                this.invalidmessage = "";
                if (this.min > 0) {
                    this.rules.min = this.min;
                    this.messages.min = this.invalidWrapper.attr("data-validation");
                }
                if (this.max > 0) {
                    this.rules.max = this.max;
                    this.messages.max = this.invalidWrapper.attr("data-validation");
                }
                if (this.minLength > 0) {
                    this.rules.minlength = this.minLength;
                    this.messages.minlength = this.invalidWrapper.attr("data-validation");
                }
                if (this.maxLength > 0) {
                    this.rules.maxlength = this.maxLength;
                    this.messages.maxlength = this.invalidWrapper.attr("data-validation");
                }
                this.dom.bind("focusin", function () {
                    if (!obj.isChecked) {
                        obj.invalidWrapper.html("");
                        obj.dom.removeClass("invalid");
                    }
                    obj.dom.trigger('widget_focusin', obj);
                    obj.dom.addClass("focus");
                });
                this.dom.bind("focusout", function () {
                    if (obj.inputValidCheck || obj.isChecked) {
                        obj.validate();
                    }
                    obj.dom.trigger('widget_focusout', obj);
                    obj.dom.removeClass("focus");
                });
            },
            numberOfFields: function () {
                return $(":input,select,textarea", this.dom).length;
            },
            show: function () {
                if (!this.isHidden) {
                    this.dom.show();
                }
            },
            hide: function () {
                this.dom.hide();
            },
            disabled: function (type) {
                if (jQuery.inArray(type, this.disabledTypes) < 0) {
                    this.disabledTypes.push(type);
                }
                this.enabled = false;
                this.clearValue();
            },
            setValue: function () {
                if (this.type == "checkbox" || this.type == "radio" || this.type == "checkboxlist" || this.type == "rating" || this.type == "order") {
                    this.value = $("input:checked", this.dom).map(function () {
                        return $(this).val();
                    }).get().join(',');
                }
                else if (this.type == "matrix") {
                    this.value = $("input:checked,input[type='text'],textarea", this.dom).not("input[id$='_text']").map(function () {
                        return $(this).val();
                    }).get().join(',');
                } else if (this.type == "cascade") {
                    this.value = $("select", this.dom).map(function () {
                        return $(this).val();
                    }).get().join(',');
                } else if (this.type == "template" || this.type == "box") {
                    this.value = $("input[type='text'],input[type='number'],textarea,select,input:checked,input", this.dom).map(function () { return $(this).val(); })
                                   .get().join(',');
                    var reg = new RegExp(",", "g");
                    var newValue = this.value.replace(reg, "");
                    if (newValue.length == 0) {
                        this.value = "";
                    }
                } else {
                    this.value = $("input,textarea,select", this.dom).val();
                }

            },
            clearValue: function () {
                $("input:checked", this.dom).attr("checked", false);
                $("text,textarea", this.dom).val("");
            },
            addMethod: function (name, method, message, param) {
                this.rules[name] = param;
                this.methods[name] = method;
                this.messages[name] = message != undefined ? message : $.askform.section.widget.messages[name];
            },
            methods: {
                required: function (value) {
                    return $.trim(value).length > 0;
                },
                minlength: function (value, param) {
                    return $.trim(value).length >= param;
                },
                maxlength: function (value, param) {
                    return $.trim(value).length <= param;
                },
                rangelength: function (value, param) {
                    var length = $.trim(value).length;
                    return (length >= param[0] && length <= param[1]);
                },
                min: function (value, param) {
                    var actual = value.split(',');
                    var newArray = new Array();
                    for (var i = 0; i < actual.length; i++) {
                        if (actual[i]) {
                            newArray.push(actual[i]);
                        }
                    }
                    return newArray.length >= param;
                },
                max: function (value, param) {
                    var actual = value.split(',');
                    var newArray = new Array();
                    for (var i = 0; i < actual.length; i++) {
                        if (actual[i]) {
                            newArray.push(actual[i]);
                        }
                    }
                    return newArray.length <= param;
                },
                range: function (value, param) {
                    return (value >= param[0] && value <= param[1]);
                },
                pattern: function (value, param) {
                    var regExp = new RegExp(param, "i");
                    return $.trim(value).length == 0 || regExp.test(value);
                }
            },
            validate: function () {
                if (!this.check() && !this.isHidden) {
                    if (this.invalidmessage && this.invalidmessage.length > 0) {
                        this.invalidWrapper.html(this.invalidmessage);
                    }
                    this.dom.addClass("invalid");
                    this.isValid = false;
                    return false;
                } else {
                    this.isValid = true;
                    this.invalidWrapper.html("");
                    this.dom.removeClass("invalid");
                    this.dom.trigger('widget_valid', this);
                    return true;
                }
            },
            check: function () {
                this.setValue();
                this.invalidmessage = "";
                if (this.enabled) {
                    var fieldCheck = true;
                    for (field in this.fields) {
                        if (!this.fields[field].check()) {
                            if (this.fields[field].invalidmessage) {
                                this.invalidmessage += this.fields[field].invalidmessage;
                            }
                            fieldCheck = false;
                        }
                    }
                    for (var i in this.rules) {
                        if (this.rules[i] && this.methods[i]) {
                            if (!this.methods[i](this.value, this.rules[i])) {
                                if (!this.invalidmessage) {
                                    this.invalidmessage = this.messages[i];
                                }
                                fieldCheck = false;
                                break;
                            }
                        }
                    }
                    if (!fieldCheck) {
                        return false;
                    }
                    //check other inputs
                    if (this.type == "matrix") {
                        var returnValue = true;
                        $("input[type='radio'],input[type='checkbox']", this.dom).each(function (index, choice) {
                            var otherInput = $("#" + $(choice).attr("id").replace(/\./g, "\\.") + "_text");
                            if ($(choice).attr("checked") && otherInput.length > 0) {
                                if (typeof (otherInput.attr("required")) != "undefined" && otherInput.val().length == 0) {
                                    returnValue = false;
                                }
                            }
                        });
                        if (!returnValue) {
                            this.invalidmessage = this.messages["required"];
                            return returnValue;
                        }
                    } else {
                        if (this.value && this.value.length > 0) {
                            var values = this.value.split(",");
                            for (var i = 0; i < values.length; i++) {
                                var otherText = $('input[id$="' + values[i] + '_text"]', this.dom);
                                otherText.show();
                                if (this.rules["required"] && otherText.length > 0) {
                                    if (typeof (otherText.attr("required")) != "undefined" && otherText.val().length == 0) {
                                        this.invalidmessage = this.messages["required"];
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }
        }
    });
    /*
    field factory 
    */
    $.askform.section.widget.field = function (f, parent) {
        this.dom = f;
        this.parent = parent;
        this.id = f.attr("id");
        this.type = f.attr("data-type") || "";
        this.min = Number(f.attr("data-min")) || 0;
        this.max = Number(f.attr("data-max")) || 0;
        this.minLength = Number(f.attr("data-minlength")) || 0;
        this.maxLength = Number(f.attr("data-maxlength")) || 4000;
        this.required = !!f.attr("data-required");
        this.invalidWrapper = $("div.fieldmessage", f);
        this.isUnique = !!f.attr("data-isunique");
        this.pattern = f.attr("data-pattern") || "";
        this.value = f.attr("data-value") || "";
        this.isDuplicateCheck = !!f.attr("data-isduplicatecheck");
        this.isChecked = false;
        this.valid = true;
        this.properties = [];
        this.init();
    }
    $.extend($.askform.section.widget.field, {
        prototype: {
            init: function () {
                var obj = this;
                this.rules = { required: this.required, pattern: this.pattern || "" },
                this.messages = { isunique: this.invalidWrapper.attr("data-uniquemessage") }
                this.invalidmessage = "";
                if (this.min > 0) {
                    this.rules.min = this.min;
                    this.messages.min = this.invalidWrapper.attr("data-validation");
                }
                if (this.max > 0) {
                    this.rules.max = this.max;
                    this.messages.max = this.invalidWrapper.attr("data-validation");
                }
                if (this.isUnique) {
                    this.rules.isunique = "rule=isunique&id=" + this.id;
                }
                this.dom.bind("focusin", function () {
                    obj.dom.trigger('field_focusin', obj);
                });
                this.dom.bind("focusout", function () {
                    obj.dom.trigger('field_focusout', obj);
                });
              //  $("input,select", this.dom).bind("change input focusin", function () {
              //      obj.check();
               // });
                $('input[id$="_text"]', this.dom).bind("focus", function () {
                    var choice = $("#" + $(this).attr("id").split("_")[0].replace(/\./g, "\\."));
                    choice.attr("checked", true);
                    choice.trigger("change");
                });
            },
            setValue: function () {
                var value = this.type == "checkbox" || this.type == "radio" || this.type == "checkboxlist" || this.type == "select" || this.type == "matrix" ? $("input:checked,select", this.dom).map(function () {
                    return $(this).val();
                }).get().join(',') : $("input,textarea", this.dom).val();
                if (this.value != value) {
                    this.isChecked = false;
                }
                this.value = value;
                this.setPropery();
            },
            setPropery: function () {
                var obj = this;
                $.each(this.properties, function (n, property) {
                    obj[property.LogicProperty] = [];
                });
                $.each(this.properties, function (n, property) {
                    var re = new RegExp(property.ValueMatch + ",", "gi");
                    if (property.ValueMatch) {
                        if (re.test(obj.value + ",")) {
                            obj[property.LogicProperty].push(property.ParamValue);
                        }
                    }

                });
            },
            clearValue: function () {
                $("input:checked", this.dom).attr("checked", false);
                $("text,textarea", this.dom).val("");
            },
            addMethod: function (name, method, message) {
                $.askform.section.widget.methods[name] = method;
                $.askform.section.widget.messages[name] = message != undefined ? message : $.askform.section.widget.messages[name];
            },
            methods: {
                required: function (value) {
                    return $.trim(value).length > 0;
                },
                isunique: function (value, param, obj) {
                    var check = true;
                    if (value && !obj.isChecked) {
                        $.ajaxSettings.async = false;
                        $.getJSON($("form").attr("action") + "&actiontype=check&callback=?&value=" + value + "&" + param + "&timstamp=" + Math.round(new Date().getTime()),
                        function (response) {
                            if (response.valid) {
                                check = true;
                            } else {
                                if (response.message) {
                                    obj.messages.isunique = response.message;
                                }
                                check = false;
                            }
                        });
                        obj.isChecked = true;
                        obj.valid = check;
                        $.ajaxSettings.async = true;
                    } else {
                        return obj.valid;
                    }
                    return check;
                },
                minlength: function (value, param) {
                    return $.trim(value).length >= param;
                },
                maxlength: function (value, param) {
                    return $.trim(value).length <= param;
                },
                rangelength: function (value, param) {
                    var length = $.trim(value).length;
                    return (length >= param[0] && length <= param[1]);
                },
                min: function (value, param) {
                    return value.split(',').length >= param;
                },
                max: function (value, param) {
                    return value.split(',').length <= param;
                },
                range: function (value, param) {
                    return (value >= param[0] && value <= param[1]);
                },
                pattern: function (value, param) {
                    var regExp = new RegExp(param, "i");
                    return regExp.test(value);
                }
            },
            validate: function () {
                if (!this.check()) {
                    if (this.invalidmessage && this.invalidmessage.length > 0) {
                        this.invalidWrapper.html(this.invalidmessage);
                    }

                    return false;
                } else {
                    this.invalidWrapper.html("");

                    return true;
                }
            },
            check: function () {
                this.setValue();
                this.invalidmessage = "";
                for (var i in this.rules) {
                    if (this.rules[i] && this.methods[i]) {
                        if (!this.methods[i](this.value, this.rules[i], this)) {
                            this.invalidmessage = this.messages[i];
                            if (this.type == "matrix") {
                                $(".fieldheader,.fieldheader_left,.fieldheader_right", this.dom).css("color", "red");
                            }
                            this.dom.trigger('field_invalid', this);
                            this.valid = false;

                            return false;
                        }
                    }
                }
                this.dom.trigger('field_valid', this);
                if (this.type == "matrix") {
                    $(".fieldheader,.fieldheader_left,.fieldheader_right", this.dom).css("color", "inherit");
                }
                this.valid = true;
                return true;
            }
        }
    });
    $.extend($.fn, {
        toaskform: function (options) {
            if (!this.length) {
                return;
            }
            var askform = $.data(this, 'askform');
            if (askform) {
                return askform;
            }
            //html5
            this.attr('novalidate', 'novalidate');

            askform = new $.askform(this, options);
            $.data(this, 'askform', askform);
            return askform;
        }
    });
})(jQuery);

jQuery.fn.timedDisable = function (time) {
    if (time == null) {
        time = 5000;
    }
    var seconds = Math.ceil(time / 1000);
    return $(this).each(function () {
        $(this).attr('disabled', 'disabled');
        var disabledElem = $(this);
        var originalText = disabledElem.attr("value");
        disabledElem.attr("value", originalText + ' (' + seconds + ')');
        var interval = setInterval(function () {
            disabledElem.attr("value", originalText + ' (' + --seconds + ')');
            if (seconds === 0) {
                disabledElem.removeAttr('disabled')
                    .attr("value", originalText);
                clearInterval(interval);
            }
        }, 1000);
    });
};
//cookie
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
jQuery.extend({
    includePath: '',
    include: function (file) {
        var files = typeof file == "string" ? [file] : file;
        for (var i = 0; i < files.length; i++) {
            var name = files[i].replace(/^\s|\s$/g, "");
            var att = name.split('.');
            var ext = att[att.length - 1].toLowerCase();
            var isCSS = ext == "css";
            var tag = isCSS ? "link" : "script";
            var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' ";
            var link = (isCSS ? "href" : "src") + "='" + $.includePath + name + "'";
            if ($(tag + "[" + link + "]").length == 0) document.write("<" + tag + attr + link + "></" + tag + ">");
        }
    }
});
